package com.fromcloudtocloud.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.SocketAddress;
import java.util.Scanner;

/**
 * @author stevejson
 */
public class NettyChatClient {
    private String ip;

    public NettyChatClient(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
    }

    private Integer port;

    public void run() throws InterruptedException {
        EventLoopGroup group = null;
        Bootstrap bootstrap = null;
        try {
            group = new NioEventLoopGroup();
            bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new NettyChartClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();

            System.out.println("----"+channelFuture.channel().localAddress().toString()+"-------");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                String line = scanner.nextLine();
                channelFuture.channel().writeAndFlush(line);

            }


            channelFuture.channel().closeFuture().sync();
        }finally {
            if(group != null){
                group.shutdownGracefully();

            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        new NettyChatClient("127.0.0.1", 9999).run();
    }
}
